export default{
	// cart 模块
	namespaced:true,
	
	state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
	// function(){
	// 	// 每个商品信息对象含6个属性
	// 	return { cart:JSON.parse( uni.getStorageSync("cart")  || "[]" )}
	// 	console.log(state.cart);
	// },
		
	mutations:{
		// 添加商品进购物车
		// addToCart(state,goods){ 
		// 	console.log(this);
		// 	const findResult = state.cart.find(x=>x.goods_id==goods.goods_id)
			
		// 	console.log(findResult);
		// 	if(!findResult){
		// 		state.cart.push(goods)
		// 	}
			
		// 	else{
		// 		findResult.goods_count++
		// 	}
		// 	console.log(state.cart);
		// 	this.commit('m_cart/saveToStorage')	
		// },
		addToCart(state, goods) {
		  const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
		
		  if (!findResult) {
		    state.cart.push(goods)
		  } else {
		    findResult.goods_count++
		  }
		
		  this.commit('m_cart/saveToStorage')
		},
		updateGoodsStatus(state,goodsObj){
			const findgoods = state.cart.find(good=>good.goods_id==goodsObj.goods_id)
			if(!findgoods)return
			findgoods.goods_status=goodsObj.goods_status
			this.commit('m_cart/saveToStorage')
		},
		updateGoodsCount(state,goodsNumObj){
			const findgoods = state.cart.find(good=>good.goods_id == goodsNumObj.goods_id)
			if(!findgoods)return
			findgoods.goods_count=goodsNumObj.goods_count
			this.commit('m_cart/saveToStorage')
		},
		updateGoodsList(state,goodsId){
			state.cart=state.cart.filter(good=>goodsId!==good.goods_id)
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state){
				uni.setStorageSync("cart",JSON.stringify(state.cart))
		},
		updateAllGoodchecked(state,flag){
			state.cart.forEach(item=>{
				console.log(item);
				item.goods_status=flag
			})
			this.commit('m_cart/saveToStorage')
		}
		
	},
	
	getters:{
		//购物车货总数
		total(state){
		 return	state.cart.reduce((pre,cur)=>pre+=cur.goods_count,0)
		},
		//购物车checked总数
		cartGoodsNumChecked(state){
		  return state.cart.filter(item=>item.goods_status==true)
											 .reduce((total,cur)=>total+=cur.goods_count,0)
		},
		//购物车选中商品总金额
		money(state){
			return state.cart.filter(item=>item.goods_status==true)
			                    .reduce((total,cur)=>total+=(cur.goods_count*cur.goods_price),0)
													.toFixed(2)
		}
		
	}
}
